package com.dsh.server.impl;


import com.dsh.entity.User;
import com.dsh.repository.UserRepository;
import com.dsh.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserRepository userRepository;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public User getUserByName(String name) {

        return userRepository.findByName(name);
    }

    @Override
    public User saveUser(User user) {
        return userRepository.save(user); // 自动判断是
    }

    @Override
    public List<User> getAllUsers() {
        String str = "!123";
        int num = 23;

        return userRepository.findAll();
    }

    @Override
    public void insertUserList() {


        for (int i = 0; i < 100; i++) {
            User user = new User();
            user.setAge(i);
            user.setEmail(i + "_@qq.com");
            user.setName("user_" + i);
            user.setAddress("address_" + i);
            user.setCreateDate(String.valueOf(new Date()));
            userRepository.save(user);
        }
    }

    @Override
    public List<User> findInAge() {
        Query query = new Query(Criteria.where("age").lt(59));
        return mongoTemplate.find(query, User.class, "user");
    }

    @Override
    public void delUser() {
        Query query = new Query(Criteria.where("age").lt(59));
        mongoTemplate.remove(query, User.class, "user");
    }

    @Override
    public void updateUserSex() {
        List<User> all = mongoTemplate.findAll(User.class);
        for (User user : all) {
            if (user.getAge()%2==0) {
                user.setSex("男");
            }else {
                user.setSex("女");
            }
          userRepository.saveAll(all);
        }
    }

}
